package com.bread.tliaswebmanagement.service.impl;

import com.bread.tliaswebmanagement.mapper.ClazzMapper;
import com.bread.tliaswebmanagement.mapper.StudentMapper;
import com.bread.tliaswebmanagement.pojo.*;
import com.bread.tliaswebmanagement.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public void add(Clazz clazz) {
        LocalDateTime now = LocalDateTime.now();
        clazz.setCreateTime(now);
        clazz.setUpdateTime(now);
        clazzMapper.insert(clazz);
    }

    @Override
    public List<Clazz> findAll() {
        return clazzMapper.findAll();
    }

    @Override
    public boolean deleteById(Integer id) {
        // 删除班级之前，查询该班级下是否有学生，如果有，则不能删除
        List<Student> list = studentMapper.list(new StudentQueryParam(null, null, id, null, null));
        if (list != null && !list.isEmpty()){
            return false;
        }else {
            clazzMapper.deleteById(id);
            return true;
        }
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        Page<Clazz> page = (Page<Clazz>) clazzMapper.list(clazzQueryParam);
        page.forEach(clazz -> {
            LocalDate today = LocalDate.now();
            if (today.isAfter(clazz.getEndDate())){
                clazz.setStatus("已结课");
            }else if (today.isBefore(clazz.getBeginDate())){
                clazz.setStatus("未开班");
            }else clazz.setStatus("在读中");
        });
        return new PageResult<Clazz>(page.getTotal(), page.getResult());
    }
}
